<template>
  <div class="container">
    <headerBar :title="local.selectGood" @changeLan="changeLan" @pageReturn="pageReturn"></headerBar>
    <div class="all" :style="{paddingTop: pdt+'px'}">
      <div class="page__bd" style="width: 100%;">
        <div class="weui-search-bar">
          <div class="weui-search-bar__form">
            <div class="weui-search-bar__box">
              <input
                type="search"
                class="weui-search-bar__input"
                v-model="inputVal"
                :placeholder="local.searchGoods"
                @confirm="inputTyping"
              />
              <div class="weui-icon-clear" v-if="inputVal.length > 0" @click="clearInput">
                <icon type="clear" size="14"></icon>
              </div>
              <span
                style=";position:absolute;right: 11px;bottom: 2px;"
                :hidden="!inputShowed"
                @click="hideInput"
              ></span>
            </div>
            <label class="weui-search-bar__label" :hidden="inputShowed" @click="showInput">
              <icon class="weui-icon-search" type="search" size="14"></icon>
              <div class="weui-search-bar__text">{{local.search}}</div>
            </label>
          </div>
          <div
            class="weui-search-bar__cancel-btn"
            :hidden="!inputShowed"
            @click="inputTyping"
          >{{local.search}}</div>
        </div>
      </div>
      <div class="filter">
        <div class="filter-left">
          <div>{{local.screen}}：</div>
          <div @click="openDialogRight">{{local.time}}</div>
          <div>|</div>
          <div @click="openDialogRight">{{local.supplier}}</div>
          <div>|</div>
          <div @click="modalFlag = true">{{local.warehouse}}</div>
        </div>
        <div class="clear-filter" @click="clearChoose">{{local.clearfilter}}</div>
      </div>
      <template v-if="selectGoodsList.length == 0">
        <div class="stock-in-record nodata-wrap">
          <img src="/static/style/block.png" class="nodata-img" />
          <p class="nodata-txt">{{local.nodata}}</p>
        </div>
      </template>
      <div class="stock-in-list" v-else>
        <div
          class="stock-in-record"
          v-for="(item, index) in selectGoodsList"
          :key="index"
          @click="submit"
          :data-item="item"
          style="margin-bottom: 11rpx;margin-top: 11rpx;"
        >
          <div class="record-supplier">
            <span :class="lang == 'zh'||lang =='zh_CN'?'w_75':'w_100'">{{local.supplier}}：</span>
            <div>{{item.supplierName}}</div>
          </div>
          <div class="record-supplier">
            <span :class="lang == 'zh'||lang =='zh_CN'?'w_75':'w_110'">{{ local.buyArea }}：</span>
            <div>{{ item.buyAreaName || ''}}</div>
          </div>
          <div class="record-goods">
            <span :class="lang == 'zh'||lang =='zh_CN'?'w_75':'w_100'">{{local.goodsName}}：</span>
            <div>{{item.goodsName}}</div>
          </div>
          <div class="record-warehouse">
            <span :class="lang == 'zh'||lang =='zh_CN'?'w_75':'w_100'">{{local.warehouseIn}}：</span>
            <div>{{item.warehouseName}}</div>
          </div>
          <div class="record-warehouse">
            <span :class="lang == 'zh'||lang =='zh_CN'?'w_75':'w_100'">{{local.storageTime}}：</span>
            <div>{{item.createTimeFormat}}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 供应商-->
    <div class="modalRight" v-if="modalFlagRight" catchtouchmove="true">
      <div style="width: 100%; height: 100%;" @click="modalFlagRight = false"></div>
      <div class="dialog">
        <div class="tip-name">{{local.goodsName}}:</div>
        <input type="number" v-model="goodsName" />
        <div class="tip-name">{{local.selectSupplier}}:</div>
        <input @click="supplierHandler()" v-model="mydata.name" />
        <div class="tip-name">{{local.selectTime}}:</div>
        <picker
          class="weui-btn flex"
          mode="date"
          :value="startTime"
          start="1999-01-01"
          end="2099-01-01"
          @change="DateChange"
        >
          <input v-model="startTimeFormat" disabled="‘disabled’" :placeholder="local.option" />
        </picker>
        <div class="tip-name">-</div>
        <picker
          class="weui-btn flex"
          mode="date"
          :value="endTime"
          start="1999-01-01"
          end="2099-01-01"
          @change="DateChangeEnd"
        >
          <input v-model="endTimeFormat" disabled />
        </picker>
        <div class="btn">
          <div class="cancel-btn" @click="closeDialogRight">{{local.cancel}}</div>
          <div class="confirm-btn" @click="selectGoodsByInput()">{{local.confirm}}</div>
        </div>
      </div>
    </div>

    <!-- 仓库弹出层 -->
    <div class="modal" v-if="modalFlag" catchtouchmove="true">
      <div style="width: 100%; height: 100%;" @click="modalFlag = false"></div>
      <div class="ware-dialog" scroll-y="true" style="border-radius: 9px;">
        <div class="header">
          {{ local.selectWarehouse }}
          <div class="text">{{ selected }}</div>
        </div>
        <div class="containera">
          <scroll-view style="height: 100%;" scroll-y="true">
            <div
              v-for="(item, index) in warehouseList"
              :key="index"
              class="ware-item"
              @click="changeWareColor(item, index)"
            >
              <div class="ware-item-left">
                <div class="num">{{ index + 1 }}</div>
                <div class="name">{{ item.warehouseName }}</div>
              </div>
              <i class="iconfont iconselect1" :style="item.selected ? 'color:#5AC8FA' : ''"></i>
            </div>
          </scroll-view>
        </div>
        <div class="bottom" @click="warehouseSearch">{{ local.confirm }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import headerBar from '@/components/headerBar'
import home from '@/api/home'
import { formatDate, filterParams } from '@/utils/index'
export default {
  components: {
    headerBar
  },
  onShow () {
    this.initMyData()
    this.initLang()
  },
  onLoad (options) {
    this.initLang()
    var myDate = new Date()
    this.startTime = formatDate(myDate, 'YYYY-MM-DD')
    this.endTime = formatDate(myDate, 'YYYY-MM-DD')
    this.page = options.page
    this.selectGoods()
    this.pdt = this.globalData.CustomBar
    this.getWarehouseList()
  },
  computed: {
    selected() {
      return this.warehouseList
        .filter(item => item.selected)
        .reduce((prv, next) => `${prv}${next.warehouseName},`, "已选择仓库:")
    },
    startTimeFormat(){
      return this.startTime ? wx.$timeFormat(this.startTime) : '' //new Date(this.startTime).$format('dd/MM/yyyy') : ''
    },
    endTimeFormat(){
      return this.endTime ? wx.$timeFormat(this.endTime) : '' //new Date(this.endTime).$format('dd/MM/yyyy') : ''
    }
  },
  methods: {
    initLang(){
      this.local = wx.getStorageSync('local')
      this.lang = wx.getStorageSync('lang')
    },
    pageReturn(){
      let pages = getCurrentPages()
      let prevPage = pages[pages.length -  2]
      prevPage.setData({
        mydata: {
          selectGoodsItem: ''
        }
      })
    },
    initMyData(){
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页面
      let myData = currPage.data.mydata;
      this.mydata.id = myData ? myData.id : ''
      this.mydata.name = myData ? myData.name : ''
    },
    clearChoose(){
      this.warehouseId = ''
      this.startTime = ''
      this.endTime = ''
      this.mydata.id = ''
      this.mydata.name = ''
      this.selectGoodsByInput()
    },
    warehouseSearch(){
      this.modalFlag = false
      this.selectGoodsAjax({warehouseId: this.warehouseId})
    },
     //仓库更换颜色
    changeWareColor(item, index) {
      this.warehouseList.forEach(element => {
        if (element.warehouseId == item.warehouseId) {
          element.selected = true
          this.warehouseId = element.warehouseId
          return
        }
        element.selected = false
      })
      this.warehouseList.push()
    },
    supplierHandler () {
      // 跳转到 客户列表
      wx.navigateTo({
        url: `../../pages/selectSupplier/index?name=supplier` //与供应商选择列表共用
      })
    },
    openDialogRight () {
      this.modalFlagRight = true
    },
    closeDialogRight () {
      this.modalFlagRight = false
      this.selectGoods()
    },
    changeLan (val, lang) {
      this.local = val
      this.lang = lang
    },
    submit(e){
      let item = e.currentTarget.dataset.item
      let pages = getCurrentPages()
      let prevPage = pages[pages.length -  2]
      prevPage.setData({
        mydata: {
          selectGoodsItem: item
        }
        // mydata[selectGoodsItem] = item
      })
      prevPage.setData({
        mydataMsg: {
          selectGoodsItem: item
        }
      })
      if (this.page =='sale') {
        // 这里要把goodsId放到数的列表里面取，
        if (!wx.getStorageSync('selectGoodsIdList')) {
          // 如果没有设置过列表数据，就设置一下W为空
          wx.setStorageSync('selectGoodsIdList', [])
          let idList = wx.getStorageSync('selectGoodsIdList')
          idList.push(item.id)
          wx.setStorageSync('selectGoodsIdList', idList)
        } else {
          let idList = wx.getStorageSync('selectGoodsIdList')
          idList.push(item.id)
          wx.setStorageSync('selectGoodsIdList', idList)
        }
      } else {
        // 这里要把goodsId放到数的列表里面取，
        if (!wx.getStorageSync('selectLogisicList')) {
          // 如果没有设置过列表数据，就设置一下W为空
          wx.setStorageSync('selectLogisicList', [])
          let idList = wx.getStorageSync('selectLogisicList')
          idList.push(item.id)
          wx.setStorageSync('selectLogisicList', idList)
        } else {
          let idList = wx.getStorageSync('selectLogisicList')
          idList.push(item.id)
          wx.setStorageSync('selectLogisicList', idList)
        }
      }
      wx.navigateBack({
          delta: 1
        })
    },
    async selectGoodsByInput () {
      this.modalFlagRight = false
      let objParams = {goodsName: this.goodsName, supplierId: this.mydata.id, 'params[startTime]': this.startTime, 'params[endTime]': this.endTime}
      //
      if (this.page == 'sale') {
        let goodsId = []
        if (wx.getStorageSync('selectGoodsIdList').length !== 0) {
          goodsId = wx.getStorageSync('selectGoodsIdList')
        }
        objParams = {'params[goodsId]': goodsId.join(), ...objParams}
      } else {
        let logisicId = []
        if (wx.getStorageSync('selectLogisicList').length !== 0) {
          logisicId = wx.getStorageSync('selectLogisicList')
        }
        objParams = {'params[goodsId]': logisicId.join(), ...objParams}
      }
      // 'params[goodsId]': goodsId.join()
      let params = filterParams(objParams)
      if (this.page == 'sale') {
        let goodsId = []
        if (wx.getStorageSync('selectGoodsIdList').length !== 0) {
          goodsId = wx.getStorageSync('selectGoodsIdList')
        }
        const {rows} = await home.selectGoods(params)
        
          rows.forEach(item=>{
          item.createTimeFormat = wx.$timeFormat(item.createTime,'time') //new Date(item.createTime).$format('dd/MM/yyyy hh:ss')
          })
        this.selectGoodsList = rows
      } else {
        let logisicId = []
        if (wx.getStorageSync('selectLogisicList').length !== 0) {
          logisicId = wx.getStorageSync('selectLogisicList')
        }
        const {rows} = await home.selectGoods(params)
          rows.forEach(item=>{
          item.createTimeFormat = wx.$timeFormat(item.createTime,'time') //new Date(item.createTime).$format('dd/MM/yyyy hh:ss')
          })
        this.selectGoodsList = rows
      }
    },
    selectGoods () {
      wx.showLoading({
        title: this.local.loading,
      })
      if (this.page == 'sale') {
        let goodsId = []
        if (wx.getStorageSync('selectGoodsIdList').length !== 0) {
          goodsId = wx.getStorageSync('selectGoodsIdList')
        }
        this.selectGoodsAjax({'params[goodsId]': goodsId.join()})
      } else {
        let logisicId = []
        if (wx.getStorageSync('selectLogisicList').length !== 0) {
          logisicId = wx.getStorageSync('selectLogisicList')
        }
        this.selectGoodsAjax({'params[goodsId]': logisicId.join()})
      }
    },
    selectGoodsAjax(paramsObj){
      paramsObj.type=2 // 只显示拆分后商品
      home.selectGoods(paramsObj).then(res => {
          wx.hideLoading()
          if (res.code != 0) {
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 2000,
            })
            return
          }
          res.rows.forEach(item=>{
          item.createTimeFormat = wx.$timeFormat(item.createTime,'time') //new Date(item.createTime).$format('dd/MM/yyyy hh:ss')
          })
          this.selectGoodsList = res.rows
        }).catch(err => {
          wx.hideLoading()
            wx.showToast({
              title: err,
              icon: "none",
              duration: 2000,
            })
        })
    },
    routerToUrl (url) {
      wx.navigateTo({
        url
      })
    },
    showInput () {
      this.inputShowed = true
    },
    hideInput () {
      this.inputVal = ''
      this.inputShowed = false
    },
    clearInput () {
      this.inputVal = ''
    },
    inputTyping () {
      this.goodsName = this.inputVal
      this.mydata.id = ''
      this.mydata.name = ''
      this.startTime = ''
      this.endTime = ''
      this.selectGoodsByInput()
    },
    DateChange (e) {
      this.startTime = e.mp.detail.value
    },
    DateChangeEnd (e) {
      this.endTime = e.mp.detail.value
    },
    getWarehouseList() {
      home.getWarehouseList().then(res => {
        this.warehouseList = res.rows
      })
    },
  },
  data () {
    return {
      startTime: '',
      endTime: '',
      modalFlag: false,
      modalFlagRight: false,
      mydata: {
        id: '',
        name: ''
      },
      lang: wx.getStorageSync('lang'),
      goodsIdList: [],
      local: wx.getStorageSync('local'),
      pdt: 66,
      saleOrderStorageList: [],
      warehouseList: [],
      warehouseId: '',
      page: '',
      inputShowed: false,
      inputVal: '',
      goodsName: '',
      logs: [],
      time: '12:01',
      selectGoodsList: []
    }
  },

  created () {
  }
}
</script>

<style scoped lang="scss">
@import 'index';
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.log-item {
  margin: 10rpx;
}
</style>
